<template>
	<div class="login-wrap">
		<div class="login-logo">
			<a class="login-logo" target="_self" href="/">
				<img width="48" height="48" alt="logo" class="login-logo-img" src="../assets/logo.png" />
				<span class="login-logo-title">编程科技导航</span>
			</a>
		</div>
		<div class="login-logo-subtitle">实用IT导航，探索优质资源</div>
		<transition name="el-zoom-in-center">
			<div class="ms-login" v-show="loginVisible">
				<div class="ms-title">欢迎登录</div>
				<div style="height: 2px;background-color:#409eff;margin: 0 10rem 0 10rem;"></div>
				<el-form :model="param" :rules="rules" ref="login" class="ms-content" label-position="right">
					<el-form-item>
						<el-input autocomplete v-model="param.username" placeholder="账号" prefix-icon="el-icon-user">
						</el-input>
					</el-form-item>
					<el-form-item style="margin-top:25px;">
						<el-input autocomplete :type="passwordType" placeholder="密码" ref="pwd" v-model="param.password"
							prefix-icon="el-icon-lock" @keyup.enter.native="submitForm()">
							<template #append>
								<el-button :icon="passwordChangeClass" @click="changePwdView($event)"></el-button>
							</template>
						</el-input>
					</el-form-item>
					<div class="tips-forget">
						<a target="_self" href="/forget">忘记密码</a>
					</div>
					<div class="login-btn">
						<el-button type="primary" @click="submitForm()" :loading="loginStatus">登录</el-button>
					</div>
					<div>
						<span class="tips-noAccount">没有账号？</span><a @click="changeCard()">立即注册</a>
					</div>
				</el-form>
			</div>
		</transition>

		<transition name="el-zoom-in-center">
			<div class="ms-register" v-show="!loginVisible">
				<div class="ms-title">欢迎注册</div>
				<div style="height: 2px;background-color:#409eff;margin: 0 10rem 0 10rem;"></div>
				<el-form :model="param" :rules="rules" ref="register" class="ms-content" label-position="right">
					<el-form-item prop="register_username">
						<el-input v-model="param.register_username" placeholder="输入新用户名" prefix-icon="el-icon-user">
						</el-input>
					</el-form-item>
					<el-form-item style="margin-top:25px;" prop="register_password1">
						<el-input type="password" placeholder="输入密码" ref="pwd" v-model="param.register_password1"
							prefix-icon="el-icon-lock" @keyup.enter.native="submitForm()">

						</el-input>
					</el-form-item>
					<el-form-item style="margin-top:25px;" prop="register_password2">
						<el-input type="password" placeholder="确认密码" ref="pwd" v-model="param.register_password2"
							prefix-icon="el-icon-lock" @keyup.enter.native="submitForm()">
						</el-input>
					</el-form-item>
					<el-form-item prop="register_email">
						<el-input v-model="param.register_email" placeholder="输入邮箱" prefix-icon="el-icon-message">
							<template #append>
								<el-select v-model="emailType" style="width: 150px">
									<el-option label="@qq.com" value="@qq.com"></el-option>
									<el-option label="@163.com" value="@163.com"></el-option>
									<el-option label="@sina.com" value="@sina.com"></el-option>
									<el-option label="@sohu.com" value="@sohu.com"></el-option>
									<el-option label="@139.com" value="@139.com"></el-option>									
									<el-option label="@189.cn" value="@189.cn"></el-option>
								</el-select>
							</template>
						</el-input>
					</el-form-item>
					<div style="margin-top: 2rem;">
					</div>
					<div class="login-btn">
						<el-button type="primary" @click="submitRigsterForm()">注册</el-button>
					</div>
					<div>
						<span class="tips-noAccount">已有账号？</span><a @click="changeCard()">立即登录</a>
					</div>
				</el-form>
			</div>
		</transition>


		<el-row style="justify-content: center;align-items: center;">
			<div class="tips-copyRights">
				{{myInfo}}
			</div>
		</el-row>
	</div>
</template>

<script>
	import {
		sha256
	} from 'js-sha256';
	import Qs from 'qs';
	import {
		ElMessage
	} from 'element-plus';
	export default {
		data() {
			const checkPassWord = (rule, value, callback) => {
				if (value === '') {
					callback(new Error('请输入您的密码'))
				} else if (value !== this.param.register_password1) {
					callback(new Error("两次输入密码不一致"))
				} else {
					callback()
				}
			}
			const checkEmail = (rule, value, callback) => {
				let emailPat=/^(.+)@(.+)$/;
				let matchArray=value.match(emailPat);
				if (value === '') {
					callback(new Error('请输入您的邮箱（无需包含邮箱@后缀）'))
				} else if (matchArray !== null) {
					callback(new Error("输入的邮箱不用包含@之后的后缀域名"))
				} else {
					callback()
				}
			}
			return {
				loginStatus: false,
				emailType: '@qq.com',
				passwordType: 'password',
				passwordChangeClass: 'el-icon-lock',
				loginVisible: true,
				myInfo: '© 2021 编程科技导航 | 页面设计＆前端开发 by 软工195 ZY',
				param: {
					username: '',
					password: '',
					register_username: '',
					register_password1: '',
					register_password2: '',
					register_email: '',
				},
				rules: {
					register_username: [{
						required: true,
						message: '账号不能为空',
						trigger: 'blur'
					}],
					register_password1: [{
						required: true,
						message: '密码不能为空',
						trigger: 'blur'
					}],
					register_password2: [{
						validator: checkPassWord,
						trigger: 'blur'
					}],
					register_email: [{
						validator: checkEmail,
						trigger: 'blur'
					}],
				}
			};
		},
		created() {
			//创建完成初始化操作...

		},
		methods: {
			changeCard() {
				this.loginVisible = !this.loginVisible;
			},

			changePwdView() {
				if (this.passwordType === 'password') {
					this.passwordType = 'text';
					this.passwordChangeClass = 'el-icon-unlock';
				} else {
					this.passwordType = 'password';
					this.passwordChangeClass = 'el-icon-lock';
				}
			},
			submitRigsterForm() {
				this.$refs.register.validate(valid => {
					if (valid) {
						let that = this;
						this.loginStatus = true;
						this.$axios({
							url: 'http://localhost:8081/userRegister',
							method: 'post',
							transformRequest: [function(data) {
								// 对 data 进行任意转换处理
								return Qs.stringify(data)
							}],
							headers: {
								
							},
							data: {
								userId: this.param.register_username,
								password: sha256(this.param.register_password1),
								email: this.param.register_email + this.emailType,
							},
							transformResponse: [function(data) {
								// 对接收的 data 进行任意转换处理
								let result = JSON.parse(data);
								console.log(result);
								if (result.code === 200) {
									ElMessage({
										message: '注册成功',
										type: 'success',
										onClose:()=>{
											that.$router.go(0)
										},
									});
								} else {
									ElMessage({
										message: result.msg,
										type: 'error',
									});
									that.loginStatus = false;

								}
								return data;
							}],
						})

					} else {
						this.$message.info('请输入账号和密码');
						return false;
					}
				});
			},
			submitForm() {
				// this.loginVisible = !this.loginVisible;
				this.$refs.login.validate(valid => {
					if (valid) {
						let that = this;
						this.loginStatus = true;
						this.$axios({
							url: 'http://localhost:8081/userLogin',
							method: 'post',
							transformRequest: [function(data) {
								// 对 data 进行任意转换处理
								return Qs.stringify(data)
							}],
							headers: {
								
							},
							data: {
								userId: this.param.username,
								password: sha256(this.param.password),
							},
							transformResponse: [function(data) {
								// 对接收的 data 进行任意转换处理
								let result = JSON.parse(data);
								console.log(result.data);
								if (result.code === 200) {
									ElMessage({
										message: '登录成功，欢迎回来：' + that.param.username + '，今日登录积分+5',
										type: 'success',
									});
									localStorage.setItem('pg_token',result.token);
									localStorage.setItem('pg_username', that.param.username);
									localStorage.setItem('pg_userInfo', JSON.stringify(result.data));
									that.$router.push({
										path:'/Home',
										// query: {userInfo: JSON.stringify(result.data)}
									});
								} else {
									ElMessage({
										message: result.msg,
										type: 'error',
									});
									that.loginStatus = false;

								}
								return data;
							}],						}).catch(function(error) {
							if (error.response) {
								// 请求成功发出且服务器也响应了状态码，但状态代码超出了 2xx 的范围
								that.$message.error("服务器响应出错，请稍后再试");
								// console.log(error.response.data);
								// console.log(error.response.status);
								// console.log(error.response.headers);
							} else if (error.request) {
								// 请求已经成功发起，但没有收到响应
								// `error.request` 在浏览器中是 XMLHttpRequest 的实例，
								// 而在node.js中是 http.ClientRequest 的实例
								that.$message.error("请求服务器错误或超时,请稍后再试");
							} else {
								// 发送请求时出了点问题
								that.$message.error("发送请求出现问题，请稍后再试");
							}
							// console.log(error.config);
							that.loginStatus = false;
						});

					} else {
						this.$message.info('请输入账号和密码');
						return false;
					}
				})
			}
		}
	};
</script>

<style>
	* {
		margin: 0;
		padding: 0;
	}

	html,
	body {
		width: 100%;
		font-family: 'Helvetica Neue', Helvetica, 'PingFang SC', 'Hiragino Sans GB',
		  'Microsoft YaHei', '微软雅黑', Arial, sans-serif;
	}

	body {
		background-color: #f0f0f0;
		/* background: url(@/assets/background-login.png) 5rem 5rem; */
		background-repeat: no-repeat;
		background-size: contain;
		-webkit-background-size: cover;
	}

	a {
		text-decoration: none;
		background-color: transparent;
		outline: none;
		cursor: pointer;
		transition: color .2s;
		color: #000000;
	}

	a:hover {
		color: #409eff;
	}

	.el-input-group {
		line-height: inherit;
	}

	.el-icon {
		line-height: 0;
	}

	.tips-copyRights {
		position: fixed;
		/* left: 0px; */
		bottom: 0px;
		width: 100%;
		height: 50px;
	}

	.tips-forget {
		text-align: right;
		font-size: 0.875rem;
	}

	.tips-noAccount {
		color: #8c8c8c;
	}

	.login-logo-img {
		vertical-align: bottom;
	}

	.login-logo {
		display: flex;
		justify-content: center;
		align-items: center;
		margin-top: 1rem;
	}

	.login-logo-title {
		margin-left: 0.5rem;
		font-size: 1.6rem;
		font-weight: 600;
		font-family: Avenir, "Helvetica Neue", Arial, Helvetica, sans-serif;
	}

	.login-logo-subtitle {
		margin-top: 0.625rem;
		color: #8c8c8c;
	}

	.login-wrap {
		/*   */
		/* background:url(../assets/noPermissions.png); */
	}

	.ms-title {
		width: 100%;
		text-align: center;
		font-size: 22px;
		color: #409eff;
		margin: 25px 0px 15px;
	}

	.ms-login {
		position: absolute;
		left: 0;
		right: 0;
		width: 450px;
		height: 350px;
		max-width: 90%;
		margin: 3.125rem auto;
		border-radius: 5px;
		background: white;
		overflow: hidden;
		box-shadow: 2px 2px 4px rgba(0, 0, 0, 0.12), 0 0 6px rgba(0, 0, 0, 0.04)
	}

	.ms-register {
		position: absolute;
		left: 0;
		right: 0;
		width: 450px;
		height: 450px;
		max-width: 90%;
		margin: 3.125rem auto;
		border-radius: 5px;
		background: white;
		overflow: hidden;
		box-shadow: 0 2px 4px rgba(0, 0, 0, 0.12), 0 0 6px rgba(0, 0, 0, 0.04)
	}

	.ms-content {
		padding: 30px 30px;
	}

	.login-btn {
		margin-top: 0.9375rem;
	}

	.login-btn button {
		width: 100%;
		height: 36px;
		text-align: center;
		margin-bottom: 10px;
	}
</style>
